<template>
	<view class="cart-container">
		<!-- 空购物车展示 -->
		<view v-if="cartItems.length === 0" class="empty-cart">
			<image src="/static/images/empty-cart.png" mode="aspectFit"></image>
			<text>购物车还是空的</text>
			<view class="empty-btn">
				<wd-button type="primary" size="large" @click="goToHome">去逛逛</wd-button>
			</view>
		</view>

		<!-- 购物车列表 -->
		<view v-else class="cart-list">
			<view class="cart-items">
				<view v-for="(item, index) in cartItems" :key="index" class="cart-item">
					<view class="item-select">
						<wd-checkbox v-model="item.selected" checked-color="#FF2C54"
							@change="handleItemSelect"></wd-checkbox>
					</view>
					<view class="item-main" @click="goToDetail(item)">
						<image class="item-image" :src="item.mainImageUrl || '/static/images/default-goods.png'"
							mode="aspectFill"></image>
						<view class="item-info">
							<view class="item-top">
								<text class="item-name">{{ item.productName }}</text>
								<view class="quantity-control" @click.stop>
									<view class="control-btn minus" :class="{ disabled: item.quantity <= 1 }"
										@click="decreaseItem(item)">
										<text>-</text>
									</view>
									<text class="quantity">{{ item.quantity }}</text>
									<view class="control-btn plus" :class="{ disabled: item.quantity >= 99 }"
										@click="increaseItem(item)">
										<text>+</text>
									</view>
								</view>
							</view>
							<view class="price-info">
								<view class="price-main">
									<text class="price-label">券后</text>
									<text class="current-price">{{ formatPrice(item.afterCouponPrice || item.price)
										}}</text>
								</view>
								<text class="separator"
									v-if="item.afterCouponPrice && item.afterCouponPrice !== item.price">|</text>
								<text v-if="item.afterCouponPrice && item.afterCouponPrice !== item.price"
									class="original-price">{{ formatPrice(item.price) }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 修改优惠券信息位置，放到固定底部 -->
			<view class="cart-footer-wrapper">
				<view v-if="cartInfo.couponName || (cartInfo.goodCouponVO && cartInfo.goodCouponVO.id)" class="coupon-info" :class="{'no-coupon': !cartInfo.couponName}">
					<view class="coupon-left">
						<text class="coupon-tag">优惠</text>
						<text v-if="cartInfo.couponName" class="coupon-name">{{ cartInfo.couponName }}</text>
						<text v-if="cartInfo.couponName && cartInfo.couponDiscountAmount" class="separator">|</text>
						<text v-if="cartInfo.couponName && cartInfo.couponDiscountAmount" class="discount-amount">已减{{ formatPrice(cartInfo.couponDiscountAmount) }}！</text>
						<text v-if="!cartInfo.couponName && cartInfo.goodCouponVO && cartInfo.goodCouponVO.id" class="no-discount">当前商品不可使用优惠券</text>
						<text class="more-discount" v-if="cartInfo.goodCouponVO && cartInfo.goodCouponVO.id">再买{{
							formatPrice(cartInfo.goodCouponVO.needConsumeAmount) }}元，可减{{
								formatPrice(cartInfo.goodCouponVO.discountAmount)
							}}元</text>
					</view>
				</view>
				<view class="cart-footer">
					<view class="footer-left">
						<wd-checkbox v-model="isAllSelected" checked-color="#FF2C54" @change="selectAll"></wd-checkbox>
						<view class="selected-text">全选</view>
						<view class="divider"></view>
						<view class="delete-btn" @click="handleDeleteSelected">
							<text>删除</text>
						</view>
					</view>
					<view class="footer-right">
						<view class="total-info">
							<view class="price-info">
								<text class="selected-count">已选 {{ selectedCount }} 件</text>
								<text class="total-label">合计:</text>
								<text class="total-price">{{ formatPrice(cartInfo.afterCouponTotalPrice ||
									cartInfo.totalPrice || 0) }}</text>
							</view>
							<text v-if="cartInfo.couponDiscountAmount" class="discount-info">共减 ¥{{
								formatPrice(cartInfo.couponDiscountAmount) }}</text>
						</view>
						<wd-button type="primary" size="large" @click="checkout"
							custom-style="background: #FF2C54; border-color: #FF2C54;">结算</wd-button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	computed
} from 'vue'
import {
	onShow
} from '@dcloudio/uni-app'
import { getCartList, getSelectedCart, increaseQuantity, decreaseQuantity, removeCartItems } from '@/api/cart'
import { formatPrice } from '@/utils/format'

const cartItems = ref([])
const cartInfo = ref({})
const isAllSelected = ref(true)

// 获取购物车数据
const loadCartData = async () => {
	try {
		// 先获取基础购物车列表
		const data = await getCartList()
		// 初始化商品数据，添加选中状态和loading状态
		cartItems.value = data.map(item => ({
			...item,
			selected: true,
			increasing: false,
			decreasing: false
		}))

		// 立即获取优惠信息
		await getSelectedCartInfo()
	} catch (error) {
		uni.showToast({
			title: '获取购物车数据失败',
			icon: 'none'
		})
	}
}

// 获取选中商品的优惠信息
const getSelectedCartInfo = async () => {
	const selectedItems = cartItems.value
		.filter(item => item.selected)
		.map(({ id, productId, quantity }) => ({
			id,
			productId,
			quantity
		}))

	if (selectedItems.length) {
		try {
			const data = await getSelectedCart(selectedItems)
			// 更新购物车总体信息
			cartInfo.value = data

			// 更新商品列表中的优惠价格
			if (data.productInCartVOList) {
				data.productInCartVOList.forEach(updatedItem => {
					const item = cartItems.value.find(i => i.id === updatedItem.id)
					if (item) {
						item.afterCouponPrice = updatedItem.afterCouponPrice
						item.productName = updatedItem.productName
						item.mainImageUrl = updatedItem.mainImageUrl
						item.price = updatedItem.price
					}
				})
			}
		} catch (error) {
			uni.showToast({
				title: '获取优惠信息失败',
				icon: 'none'
			})
		}
	} else {
		cartInfo.value = {}
	}
}

// 修改商品选择处理
const handleItemSelect = () => {
	updateSelection()
	getSelectedCartInfo() // 重新获取优惠信息
}

const selectAll = async (value) => {
	cartItems.value.forEach(item => {
		item.selected = value.value
	})
	isAllSelected.value = value.value
	await getSelectedCartInfo() // 重新获取优惠信息
}

// 增减商品数量的方法中也需要更新
const increaseItem = async (item) => {
	if (item.quantity >= 99 || item.increasing) return

	item.increasing = true
	try {
		const cartItemId = parseInt(item.id)
		if (isNaN(cartItemId)) {
			throw new Error('无效的商品ID')
		}
		await increaseQuantity(cartItemId)
		item.quantity++
		await getSelectedCartInfo() // 使用新方法获取优惠信息
	} catch (error) {
		uni.showToast({
			title: '增加数量失败',
			icon: 'none'
		})
	} finally {
		item.increasing = false
	}
}

const decreaseItem = async (item) => {
	if (item.quantity <= 1 || item.decreasing) return

	item.decreasing = true

	try {
		const cartItemId = parseInt(item.id)
		if (isNaN(cartItemId)) {
			throw new Error('无效的商品ID')
		}

		await decreaseQuantity(cartItemId)
		item.quantity--
		await getSelectedCartInfo() // 使用新方法获取优惠信息
	} catch (error) {
		console.log(error)
		uni.showToast({
			title: '减少数量失败',
			icon: 'none'
		})
	} finally {
		item.decreasing = false
	}
}

onShow(() => {
	loadCartData()
})

// 计算属性
const selectedCount = computed(() => {
	return cartItems.value.filter(item => item.selected).length
})

// 方法
const goToHome = () => {
	uni.switchTab({
		url: '/pages/index/index'
	})
}

const updateSelection = () => {
	isAllSelected.value = cartItems.value.every(item => item.selected)
}

const checkout = () => {
	const selectedItems = cartItems.value.filter(item => item.selected)
	if (selectedItems.length === 0) {
		uni.showToast({
			title: '请选择要结算的商品',
			icon: 'none'
		})
		return
	}

	// 准备传递到结算页面的商品数据
	const checkoutItems = selectedItems.map(item => ({
		id: item.productId,
		name: item.productName,
		price: item.price || item.afterCouponPrice, // 优先使用优惠后价格
		quantity: item.quantity,
		image: item.mainImageUrl
	}))


	const goToJson = {
		checkoutItems,
		totalPrice: cartInfo.value.totalPrice
	}

	// 将商品数据编码后传递到结算页面
	const cartItemsStr = encodeURIComponent(JSON.stringify(goToJson))
	
	uni.navigateTo({
		url: `/pages/order/checkout?cartItems=${cartItemsStr}&cart=${true}`,
		fail: (err) => {
			console.error('跳转结算页面失败:', err)
			uni.showToast({
				title: '跳转失败',
				icon: 'none'
			})
		}
	})
}

// 修改删除选中商品的方法
const handleDeleteSelected = async () => {
	const selectedItems = cartItems.value.filter(item => item.selected)
	if (selectedItems.length === 0) {
		uni.showToast({
			title: '请选择要删除的商品',
			icon: 'none'
		})
		return
	}

	try {
		// 修改 showModal 的使用方式
		const res = await new Promise((resolve, reject) => {
			uni.showModal({
				title: '提示',
				content: '确定要删除选中的商品吗？',
				confirmColor: '#FF2C54',
				success: (result) => {
					resolve(result)
				},
				fail: (error) => {
					reject(error)
				}
			})
		})

		if (res.confirm) {
			// 调用删除接口
			const itemIds = selectedItems.map(item => item.id)
			await removeCartItems(itemIds)

			// 从列表中移除选中的商品
			cartItems.value = cartItems.value.filter(item => !item.selected)
			// 重新获取购物车信息
			await getSelectedCartInfo()

			uni.showToast({
				title: '删除成功',
				icon: 'success'
			})
		}
	} catch (error) {
		console.error('删除失败:', error)
		uni.showToast({
			title: '删除失败',
			icon: 'none'
		})
	}
}

// 添加跳转到商品详情的方法
const goToDetail = (item) => {
	uni.navigateTo({
		url: `/pages/product/detail?id=${item.productId}`
	})
}
</script>

<style lang="scss">
.cart-container {
	min-height: 100vh;
	background: #f8f8f8;
	padding: 0 20rpx;

	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 200rpx;
		margin: 0 30rpx;

		image {
			width: 240rpx;
			height: 240rpx;
			margin-bottom: 30rpx;
		}

		text {
			color: #999;
			font-size: 28rpx;
			margin-bottom: 40rpx;
		}

		.empty-btn {
			width: 240rpx;
		}
	}

	.cart-list {
		padding-bottom: 200rpx;

		.cart-items {
			.cart-item {
				display: flex;
				align-items: stretch;
				padding: 20rpx;
				padding-left: 0;
				background: #fff;
				margin-bottom: 20rpx;
				border-radius: 12rpx;

				.item-select {
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 0 12rpx;
					margin-left: 12rpx;

					:deep(.wd-checkbox) {
						margin: 0;
						transform: scale(0.9);

						.wd-checkbox__label {
							display: none;
						}
					}
				}

				.item-main {
					flex: 1;
					display: flex;
					gap: 20rpx;
					overflow: hidden;

					&:active {
						opacity: 0.95;
						background: #fafafa;
					}

					.item-image {
						width: 160rpx;
						height: 160rpx;
						border-radius: 12rpx;
						background-color: #f5f5f5;
						flex-shrink: 0;
					}

					.item-info {
						flex: 1;
						min-width: 0;
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						height: 160rpx;
						overflow: hidden;

						.item-top {
							display: flex;
							justify-content: space-between;
							align-items: flex-start;
							gap: 20rpx;
							width: 100%;
							overflow: hidden;

							.item-name {
								flex: 1;
								font-size: 28rpx;
								font-weight: 500;
								overflow: hidden;
								white-space: nowrap;
								text-overflow: ellipsis;
								line-height: 40rpx;
								max-width: calc(100% - 120rpx);
							}

							.quantity-control {
								flex-shrink: 0;
								width: auto;
								display: flex;
								align-items: center;
								height: 48rpx;
							}
						}

						.price-info {
							display: flex;
							align-items: center;
							gap: 12rpx;

							.price-main {
								display: flex;
								align-items: baseline;

								.price-label {
									font-size: 22rpx;
									color: #ff4d4f;
									margin-right: 4rpx;
								}

								.current-price {
									color: #ff4d4f;
									font-size: 30rpx;
									font-weight: bold;

									&::before {
										content: '¥';
										font-size: 22rpx;
										margin-right: 2rpx;
									}
								}
							}

							.separator {
								color: #ddd;
								font-size: 22rpx;
								margin: 0 4rpx;
							}

							.original-price {
								color: #ff4d4f;
								font-size: 26rpx;
								font-weight: bold;

								&::before {
									content: '¥';
									font-size: 22rpx;
									margin-right: 2rpx;
								}
							}
						}
					}
				}
			}
		}

		// 修改底部布局结构
		.cart-footer-wrapper {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			z-index: 99;
			background: #fff;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

			// 优惠券信息样式
			.coupon-info {
				padding: 16rpx 40rpx;
				background: #FF2C54;
				border-bottom: 2rpx solid #f5f5f5;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.coupon-left {
					display: flex;
					align-items: center;
					gap: 8rpx;

					.coupon-tag {
						font-size: 20rpx;
						color: #FF2C54;
						background: #fff;
						padding: 2rpx 8rpx;
						border-radius: 4rpx;
					}

					.coupon-name {
						font-size: 24rpx;
						color: #fff;
					}

					.separator {
						font-size: 24rpx;
						color: rgba(255, 255, 255, 0.6);
						margin: 0 8rpx;
					}

					.more-discount {
						font-size: 24rpx;
						color: #fff;
					}
				}

				.discount-amount {
					font-size: 24rpx;
					color: #fff;
					font-weight: 500;
				}

				&.no-coupon {
					background: #f5f5f5;
					border-bottom: none;

					.coupon-left {
						opacity: 0.8;
					}

					.coupon-tag {
						color: #666;
						background: #fff;
					}

					.no-discount {
						font-size: 24rpx;
						color: #666;
					}

					.more-discount {
						color: #FF2C54;
						font-weight: 500;
					}
				}
			}

			// 底部结算栏样式调整
			.cart-footer {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx 40rpx;
				background: #fff;

				.footer-left {
					display: flex;
					align-items: center;

					:deep(.wd-checkbox) {
						margin: 0;
					}

					.divider {
						width: 1px;
						height: 24rpx;
						background: #eee;
						margin: 0 15rpx;
					}

					.selected-text {
						font-size: 26rpx;
						color: #999;
					}

					.delete-btn {
						display: flex;
						align-items: center;
						gap: 6rpx;
						font-size: 26rpx;
						color: #ff0000de;
						padding: 12rpx 0;
						transition: all 0.2s;

						:deep(.wd-icon) {
							position: relative;
							top: 1rpx;
							color: #999;
							transition: all 0.2s;
						}

						&:active {
							color: #ff4d4f;

							:deep(.wd-icon) {
								color: #ff4d4f;
								transform: scale(0.9);
							}
						}
					}
				}

				.footer-right {
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: flex-end;
					gap: 24rpx;

					.total-info {
						display: flex;
						flex-direction: column;
						align-items: flex-end;

						.price-info {
							display: flex;
							align-items: center;
							gap: 12rpx;
							margin-bottom: 4rpx;

							.selected-count {
								font-size: 22rpx;
								color: #666;
							}

							.total-label {
								font-size: 22rpx;
								color: #666;
							}

							.total-price {
								color: #ff4d4f !important;
								font-size: 28rpx;
								font-weight: bold;

								&::before {
									content: '¥';
									font-size: 22rpx;
									margin-right: 2rpx;
								}
							}
						}

						.discount-info {
							font-size: 22rpx;
							color: #ff4d4f !important;
						}
					}

					:deep(.wd-button) {
						margin: 0;
						width: 160rpx;
						font-size: 32rpx;
						border-radius: 40rpx;
						height: 72rpx;
						line-height: 72rpx;
					}
				}
			}
		}
	}

	// 修改数量控制器样式
	.quantity-control {
		display: flex;
		align-items: center;
		gap: 8rpx;
		height: 48rpx;

		.control-btn {
			width: 48rpx;
			height: 48rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background: #F7F8FA;
			border-radius: 50%;
			position: relative;
			transition: all 0.2s;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

			text {
				font-size: 28rpx;
				color: #666;
				font-weight: 400;
				line-height: 1;
				position: relative;
				top: -1rpx;
			}

			&.minus text {
				top: -2rpx;
			}

			&.disabled {
				background: #F7F8FA;
				opacity: 0.6;
				box-shadow: none;

				text {
					color: #C8C9CC;
				}
			}

			&:active:not(.disabled) {
				background: #EBEDF0;
				transform: scale(0.95);
				box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.05);
			}
		}

		.quantity {
			min-width: 48rpx;
			text-align: center;
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
		}
	}
}

@keyframes pulse {
	0% {
		opacity: 0.8;
	}

	50% {
		opacity: 1;
	}

	100% {
		opacity: 0.8;
	}
}
</style>